package xin.lhuo.we.server.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.lhuo.we.server.dao.NodeCategoryMapper;
import xin.lhuo.we.server.dao.NodeMapper;
import xin.lhuo.we.server.entity.Node;
import xin.lhuo.we.server.entity.NodeCategory;
import xin.lhuo.we.server.enums.ResultEnum;
import xin.lhuo.we.server.exception.WeException;
import xin.lhuo.we.server.properties.QiNiuProperties;
import xin.lhuo.we.server.service.INodeService;
import xin.lhuo.we.server.utils.QiNiuUtil;

import java.util.List;

import static xin.lhuo.we.server.utils.QiNiuUtil.getDownloadUrlByKey;

/**
 * @author Lhuo
 * @date 2019/6/29 22:11
 */
@Service
public class NodeServiceImpl implements INodeService {
    @Autowired
    private NodeCategoryMapper nodeCategoryMapper;

    @Autowired
    private NodeMapper nodeMapper;

    @Autowired
    private QiNiuProperties qiNiuProperties;

    @Override
    public List<NodeCategory> getCategory(Integer userId) {
        return nodeCategoryMapper.getNodeCategory(userId);
    }

    @Override
    public void createCategory(NodeCategory nodeCategory) {

        int count = nodeCategoryMapper.checkName(nodeCategory.getUserId(), nodeCategory.getName());
        if (count > 0) {
            throw new WeException(ResultEnum.PARAM_ERROR.getCode(), "类型已存在，不能重复创建");
        }
        nodeCategoryMapper.saveNodeCategory(nodeCategory);
    }

    @Override
    public List<Node> getNode(Integer userId) {
        List<Node> nodeList = nodeMapper.getNode(userId);
        nodeList.forEach(item -> {
            if (item.getImageKey() != null){
                item.setImageUrl(getDownloadUrlByKey(qiNiuProperties, item.getImageKey()));
            }
        });
        return nodeList;
    }

    @Override
    public Node getNodeById(Integer id) {
        return nodeMapper.getNodeById(id);
    }

    @Override
    public void createNode(Node node) {
        nodeMapper.saveNode(node);
    }

    @Override
    public String getQiNiuToken() {
        return QiNiuUtil.getUpTokenNoCallBack(qiNiuProperties);
    }
}
